﻿using System.Data.SQLite;
using CompactMapper.Orm.Contracts;
using CompactMapper.Orm.UnitOfWork.Commands.Interfaces;
using CompactMapper.Orm.UnitOfWork.Mappings;

namespace CompactMapper.Orm.UnitOfWork.Commands.Implementations
{
    internal class DeleteCommand : Command, IDeleteCommand
    {
        public DeleteCommand(Table table)
            : base(table)
        {
        }

        #region IDeleteCommand Members

        public void Run(SQLiteConnection connection, IKey key)
        {
            using (var cmd = new SQLiteCommand(CreateDeleteText(Table), connection))
            {
                AddDeleteParameters(cmd, key);
                cmd.ExecuteNonQuery();
            }
        }

        public void Run(SQLiteConnection connection)
        {
            using (var cmd = new SQLiteCommand(new SqlBuilder().DeleteAllFrom(Table).ToString(), connection))
            {
                cmd.ExecuteNonQuery();
            }
        }

        #endregion

        private static string CreateDeleteText(Table table)
        {
            return new SqlBuilder().DeleteFrom(table).ToString();
        }

        private static void AddDeleteParameters(SQLiteCommand command, IKey key)
        {
            command.Parameters.Clear();
            command.Parameters.Add(new SQLiteParameter("@Key", key.Value));
        }
    }
}